package com.levi.rabbitmq.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * Direct交换机模式  根据Routingkey路由到对应的消费者
 */
public class DirectProducer {

    public static final String EXCHANGE_NAME = "direct";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置rabbitmq地址
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //建立连接
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();
        //设置交换机模式为fanout广播模式
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        //发送消息
        String message = "direct  error  message";
        //                       交换机     队列名称         额外配置          要发送的消息
        channel.basicPublish(EXCHANGE_NAME, "error", null, message.getBytes(StandardCharsets.UTF_8));
        System.out.println("发送了消息: 消息级别为： error  " + message);
         message = "direct  waring  message ";
        channel.basicPublish(EXCHANGE_NAME, "waring", null, message.getBytes(StandardCharsets.UTF_8));
        System.out.println("发送了消息: 消息级别为： waring  " + message);
        message = "direct  info  message ";
        channel.basicPublish(EXCHANGE_NAME, "info", null, message.getBytes(StandardCharsets.UTF_8));
        System.out.println("发送了消息: 消息级别为： info  " + message);

        //关闭连接
        channel.close();
        connection.close();
    }
}
